package ntd.util.frame.action.function.map.geo.json;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.StaticLog;
import ntd.util.UtilCatch;
import ntd.util.frame.data.factory.FactoryData;

import javax.sql.DataSource;

public class ClimbAliyun {
    private static String geoJsonBaseUrl = "http://geo.datav.aliyun.com/areas_v3/bound/";

    private static Db db = Db.use(FactoryData.dataSource());

    public static void main(String[] args) {
        climb("100000");
    }

    private static void climb(String adcode) {
        StaticLog.info("adcode ---------- " + adcode);
        if (StrUtil.isBlank(adcode)) {
            return;
        }
        JSONObject jsonObject = JSONUtil.parseObj(queryGenJson(adcode));

        JSONArray features = jsonObject.getJSONArray("features");
        if (CollectionUtil.isEmpty(features)) {
            return;
        }
        for (int i = 0; i < features.size(); i++) {
            climb(features.getJSONObject(i).getByPath(".properties.adcode", String.class));
        }
    }

    private static String queryGenJson(String adcode) {
        String res = HttpUtil.get(geoJsonBaseUrl + adcode + "_full.json");

        StaticLog.info(res);

        UtilCatch.tryCatchNoRes(() -> {
            if (JSONUtil.isTypeJSON(res)) {
                Entity entity = new Entity("data_geojson");
                entity.set("id", IdUtil.simpleUUID());
                entity.set("adcode", adcode + "_full");
                entity.set("geojson", res);
                db.insert(entity);
            }
        });

        UtilCatch.tryCatchNoRes(() -> {
            String data = HttpUtil.get(geoJsonBaseUrl + adcode + ".json");
            if (JSONUtil.isTypeJSON(data)) {
                Entity entity = new Entity("data_geojson");
                entity.set("id", IdUtil.simpleUUID());
                entity.set("adcode", adcode);
                entity.set("geojson", data);
                db.insert(entity);
            }
        });

        return res;
    }
}
